package gi18n_lang

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	v1 "video-api/api/v1"
	"video-api/internal/service"
	"video-api/utility"
	"video-api/utility/gi18n_lang"
	"video-api/utility/validate"
)

func init() {
	service.RegisterLangService(&iLang{})
}

type iLang struct{}

func (i *iLang) LangSwitch(ctx context.Context, lang string) (string, error) {
	str := gi18n_lang.TranslateLang(ctx, lang)
	return str, nil
}

func (i *iLang) WriteLangFile(ctx context.Context, req *v1.WriteLangReq) error {
	isValid := validate.VerifySignature(ctx, validate.SignParam{Timestamp: req.Timestamp, Signature: req.Signature})
	if !isValid {
		return errors.New("签名验证失败")
	}
	dir, err := os.Getwd()
	if err != nil {
		fmt.Println("WriteLangFile Getwd err:", err)
		return nil
	}
	for _, v := range req.Content {
		pathFile := filepath.Join(dir, "manifest", "i18n", fmt.Sprintf("%s.json", v.Lang))
		jsonData := []byte("")
		jsonData, err = json.Marshal(v.Content)
		if err != nil {
			log.Fatal(err)
			return err
		}
		err = utility.WriteJSONToFile(pathFile, string(jsonData))
		if err != nil {
			return err
		}
	}
	return nil
}
